//
//  String+Extension.swift
//  SmartEyeForPatient
//
//  Created by QDSG on 2021/4/2.
//

import Foundation
import UIKit

extension String {
    func subString(from index: Int) -> String {
        return String(self[self.index(startIndex, offsetBy: index)...])
    }
    
    func substring(with range: Range<Int>) -> String {
        let start = index(startIndex, offsetBy: range.lowerBound)
        let end = index(startIndex, offsetBy: range.upperBound)
        return String(self[start..<end])
    }

    /// String使用下标截取字符串
    /// string[index, length] 例如："abcdefg"[3, 2] // de
    func subString(index: Int, length: Int) -> String {
        let start = self.index(startIndex, offsetBy: index)
        let end = self.index(start, offsetBy: length)
        return String(self[start..<end])
    }
    
    var intValue: Int {
        guard let intValue = Int(self) else { return 0 }
        return intValue
    }
    
    var floatValue: Float {
        guard let value = Float(self) else { return 0 }
        return value
    }
    
    static var randomOfFive: String {
        return String(format: "%d", Int(arc4random_uniform(89999) + 10000))
    }
}

extension String {
    func height(width: CGFloat, font: UIFont) -> CGFloat {
        let rect = (self as NSString).boundingRect(with: CGSize(width: width, height: .greatestFiniteMagnitude),
                                                   options: [.usesLineFragmentOrigin, .usesFontLeading],
                                                   attributes: [NSAttributedString.Key.font: font],
                                                   context: nil)
        return ceil(rect.size.height)
    }
    
    func heightForSingleLine(font: UIFont) -> CGFloat {
        let size = (self as NSString).size(withAttributes: [NSAttributedString.Key.font: font])
        return ceil(size.height)
    }
    
    func width(height: CGFloat, font: UIFont) -> CGFloat {
        let rect = (self as NSString).boundingRect(with: CGSize(width: .greatestFiniteMagnitude, height: height),
                                                   options: [.usesLineFragmentOrigin, .usesFontLeading],
                                                   attributes: [NSAttributedString.Key.font: font],
                                                   context: nil)
        return ceil(rect.size.width)
    }
}
